import { createRouter, createWebHashHistory } from "vue-router"
import mainStore from "@/store"
import {getUserInformation} from '@/api/index'

const Login = () => import("../views/LoginPage.vue")
const Home = () => import("@/views/home/HomePage.vue")

// 定义静态路由
const staticRoutes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path:'/home',
    component:Home,
  }
]

// 定义动态路由
function dynamicRoutes(data){
  let HomeRoute=staticRoutes.filter(x=>x.path==='/home')[0]
  HomeRoute.children=[]
  data.forEach(item=>{
    HomeRoute.children.push(
      {
        path:item.path,
        name:item.name,
        component:()=>import(`@/views/home/content/${item.component}/index.vue`)
      }
    )
  })
  return HomeRoute;
}


// 路由守卫
router.beforeEach(async(to,from,next)=>{
    if(to.path==='/login'){
       next()
    }else{
       if(mainStore()&&mainStore.navbarData.length===0){
        // 发送网络请求
        const res=await getUserInformation
        // 将数据缓存到pinina中
        mainStore.setnavbarData(res.data.res)
        // 动态处理路由
        let addDynamicRoutes=dynamicRoutes(res.data.res)
        // 动态添加路由
        router.addRoute(addDynamicRoutes)
        next({path:to.path})//这样跳转，刷新页面数据不会丢失，不然刷新页面，store中数据会丢失
       }
    }
})


// 创建路由
const router = createRouter({
  history: createWebHashHistory(),
  staticRoutes,
})

export default router
